package com.learn.concurrent.itcast.thread.interaction.example2;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * https://zhuanlan.zhihu.com/p/109211584
 */
public class ConditionTest1 {

    final Lock lock=  new ReentrantLock();
    final Condition condition=lock.newCondition();

    public static void main(String[] args) {
        ConditionTest1 test=new ConditionTest1();
        Consumer consumer=test.new Consumer();
        Producer producer=test.new Producer();

        consumer.start();
        producer.start();
    }

    class Consumer extends Thread{

        @Override
        public void run() {
            consume();
        }

        private void consume(){
            try {
                lock.lock();
                System.out.println("我在等一个新信号"+this.currentThread().getName());
                condition.await();

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                System.out.println("我拿到一个信号"+this.currentThread().getName());
                lock.unlock();
            }
        }
    }

    class Producer extends Thread{
        @Override
        public void run() {
            produce();
        }

        private void produce(){
            try {
                lock.lock();
                System.out.println("我拿到锁"+this.currentThread().getName());
                TimeUnit.SECONDS.sleep(5);
                System.out.println("我发出了一个信号："+this.currentThread().getName());
                condition.signalAll();

            } catch (Exception e) {
                e.printStackTrace();
                lock.unlock();
            } finally {
            }
        }
    }

}
